package com.mhy.tvcontrol

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.view.MotionEvent
import android.widget.CheckBox
import android.widget.ImageButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.Button
import com.mhy.tvcontrol.BluetoothService.MESSAGE_TOAST
import kotlin.system.exitProcess

/*
	//HL-1小车驱动接线定义
    #define Left_moto_go      {P0_0=1,P0_1=0;}    //左边电机向前走
	#define Left_moto_back    {P0_0=0,P0_1=1;}    //左边电机向后转
	#define Left_moto_Stop    {P0_0=0,P0_1=0;}    //左边电机停转
	#define Right_moto_go     {P0_2=1,P0_3=0;}	//右边电机向前走
	#define Right_moto_back   {P0_2=0,P0_3=1;}	//右边电机向后走
	#define Right_moto_Stop   {P0_2=0,P0_3=0;}	//右边电机停转

	#define left     'C'
    #define right    'D'
	#define up       'A'
    #define down     'B'
	#define stop     'F'
 *
 */
class BlueToothActivity : AppCompatActivity(), SensorEventListener {
    companion object {
        private val REQUEST_CONNECT_DEVICE = 1
        private val REQUEST_ENABLE_BT = 0


    }

    var Isconnect = false
    var sensorValueX = 0f
    var sensorValueY = 0f
    private var device: BluetoothDevice? = null

    private var mBluetoothAdapter: BluetoothAdapter? = null

    //重力感应
    private var sensorManager: SensorManager? = null
    private var sensorbtn: CheckBox? = null
    private var blue_exit: CheckBox? = null
    private var bluetoothbtn: Button? = null
    private var controlView: BuleCarControlView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_blue_car)
//        window.setFeatureInt(7, R.layout.custom_title)
        sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager?

        sensorbtn = findViewById<CheckBox>(R.id.buttonsensor)
        blue_exit = findViewById<CheckBox>(R.id.button_exit)
        bluetoothbtn = findViewById<Button>(R.id.buttonbt)
        controlView = findViewById<BuleCarControlView>(R.id.control_view)
        sensorbtn?.isClickable = false //不可用

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "您的手机不支持蓝牙", Toast.LENGTH_LONG).show()
            return
        }
        sensorbtn?.setOnCheckedChangeListener { buttonView, isChecked ->
            if (!isChecked) {
                Isconnect = false
                sensorManager?.unregisterListener(this@BlueToothActivity)
            } else if (BluetoothService.connectedThread != null) {
                sensorManager?.registerListener(
                    this@BlueToothActivity,
                    sensorManager?.getDefaultSensor(REQUEST_CONNECT_DEVICE), REQUEST_ENABLE_BT
                )
                Isconnect = true
                SendDataR().start()
            } else {
                Toast.makeText(applicationContext, "蓝牙未连接", Toast.LENGTH_LONG).show()
            }
        }
        bluetoothbtn?.setOnClickListener {
            startActivityForResult(
                Intent(this@BlueToothActivity, DeviceListActivity::class.java),
                REQUEST_CONNECT_DEVICE
            )
        }
        if (mBluetoothAdapter?.isEnabled == false) {
            startActivityForResult(
                Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),
                REQUEST_ENABLE_BT
            )
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 0) {
            if (resultCode == 0) {
                Toast.makeText(
                    this,
                    "Bluetooth_untapped",
                    Toast.LENGTH_LONG
                ).show()
                finish()
            }
        }
        if (requestCode == REQUEST_CONNECT_DEVICE && resultCode == -1) {
            val address = data?.extras?.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS)
            device = mBluetoothAdapter?.getRemoteDevice(address)
            Log.e("address", "$address")
            Log.e("device", device.toString())
            device?.let { controlView?.connect(it) }
            sensorbtn!!.isClickable = true
        }
    }

    override fun onSensorChanged(e: SensorEvent) {
        sensorValueX = e.values[REQUEST_ENABLE_BT]
        sensorValueY = e.values[REQUEST_CONNECT_DEVICE]
    }

    inner class SendDataR : Thread() {
        override fun run() {
            while (Isconnect) {
                if (sensorValueX > 5.0f && sensorValueY > -1.0f && sensorValueY < 3.0f) {
                    controlView?.send(BuleCarControlView.bytedown)
                    try {
                        sleep(100)
                    } catch (e1: InterruptedException) {
                        e1.printStackTrace()
                    }
                }
                if (sensorValueX < 2.0f && sensorValueY > -1.0f && sensorValueY < 3.0f) {
                    controlView?.send(BuleCarControlView.byteup)
                    try {
                        sleep(100)
                    } catch (e12: InterruptedException) {
                        e12.printStackTrace()
                    }
                }
                if (sensorValueY < -1.0f) {
                    controlView?.send(BuleCarControlView.byteleft)
                    try {
                        sleep(100)
                    } catch (e13: InterruptedException) {
                        e13.printStackTrace()
                    }
                }
                if (sensorValueY > 3.0f) {
                    controlView?.send(BuleCarControlView.byteright)
                    try {
                        sleep(100)
                    } catch (e14: InterruptedException) {
                        e14.printStackTrace()
                    }
                }
            }
        }
    }


    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode != KeyEvent.KEYCODE_BACK || event.repeatCount != 0) {
            return false
        }
        AlertDialog.Builder(this)
            .setTitle("系统提示")
            .setMessage("确定要退出吗？")
            .setIcon(R.mipmap.ic_launcher)
            .setPositiveButton("确定") { dialog, which ->
                if (blue_exit?.isChecked == true) {
                    mBluetoothAdapter?.disable()
                }
                dialog.cancel()
                finish()
                exitProcess(1)
            }
            .setNeutralButton("取消") { dialog, which ->
                dialog.cancel()
            }
            .create()
            .show()
        return false
    }

    override fun onDestroy() {
        super.onDestroy()
        Isconnect = false
        sensorManager?.unregisterListener(this)
    }
}